Lesson 5: Code Reuse with Functions (Introduction)
Functions are named, self-contained blocks of organized, reusable code designed to perform a single, related action. They are the fundamental tool for achieving modularity in programming, allowing complex systems to be broken down into smaller, manageable units.
1. The Power of Code Reuse
The defining benefit of functions is the ability to write a piece of logic once and execute it hundreds of times without copying and pasting. This reduces errors, improves efficiency, and makes large applications easier to maintain and scale. This principle is often referred to as DRY (Don't Repeat Yourself).
This lesson focuses on mastering the structure of defining a function, passing input information (arguments), and managing output results. We will use functions to abstract complex mathematical operations, such as calculating the area of a circle $A = \pi r^2$, using reusable logic.
2. Defining and Calling Functions
- Definition: Functions are created using the
defkeyword, followed by the function name and parentheses. - Parameters: These are variables listed inside the function's parentheses, acting as placeholders for input values (arguments) that the function needs to execute its task.
- Invocation (Calling): To execute a function, you simply write its name followed by parentheses, passing the required arguments.
def statement, to determine exactly where the function block begins and ends.